<template>
  <div>
    <div ref="editor" style="text-align: left;"></div>
  </div>
</template>

<script>
import config from '@/config'
import E from 'wangeditor';
import {
  fetchImg,
} from '@/api/main'
export default {
  name: 'WangEditor',
  data() {
    return {
      editor: null, // WangEditor 实例
    };
  },
  props: {
    content: {
      type: String,
      default: ''
    }
  },
  watch: {
    // 当父组件传入的 content 变化时，更新编辑器内容
    content(newContent) {
      if (this.editor && newContent !== this.editor.txt.html()) {
        this.editor.txt.html(newContent);
      }
    }
  },
  methods: {
    async changeImg(htmlString) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, 'text/html');
      const imgTags = Array.from(doc.getElementsByTagName('img'));
      const srcValues = imgTags.map(tag => tag.getAttribute('src'));
      if (!srcValues.length) {
        this.$emit('getHtmlContent', htmlString);
      } else {
        for (let i = 0; i < srcValues.length; i++) {
          let obj = {}
          obj.img_url = srcValues[i]
          let res = await fetchImg(obj)
					if (res.code == 0) {
            htmlString = htmlString.replace(srcValues[i], res.data)
          }
        }
        this.$emit('getHtmlContent', htmlString);
      }
    },
  },
  mounted() {
    let _this = this
    // 初始化 WangEditor
    this.editor = new E(this.$refs.editor);
    this.editor.config.onchange = () => {
      // 编辑器内容变化时，触发 input 事件传递给父组件
      this.changeImg(this.editor.txt.html())
      //this.$emit('getHtmlContent', new_html_str);
    };
    // 配置菜单和其他设置
    this.editor.config.menus = [
      'head',  // 标题
      'bold',  // 粗体
      'italic',  // 斜体
      'underline',  // 下划线
      "justify", // 对齐方式
      "fontSize", // 字号
      "fontName", // 字体
      "foreColor", // 文字颜色
      "backColor", // 背景颜色
      'image',  // 图片
      'list',  // 列表
      'undo',  // 撤销
      'redo',  // 重做
    ];
    this.editor.config.zIndex = 1000;
    this.editor.config.uploadImgServer = config.baseUrl.dev+'/img/upload-img';
    this.editor.config.uploadFileName = 'file'
    this.editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png']
    this.editor.config.uploadImgHooks = {
      customInsert: function(insertImgFn, result) {
	      insertImgFn(result.data)
	    }
    }
    this.editor.create();
    // 设置初始内容
    if (this.content) {
      this.editor.txt.html(this.content);
    }
  },
  beforeDestroy() {
    // 销毁编辑器实例，释放资源
    if (this.editor) {
      this.editor.destroy();
    }
  }
};
</script>

<style scoped>
/* 可以根据需要调整编辑器样式 */
</style>